import os
from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse, FileResponse, HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pathlib import Path
from loguru import logger

from api.endpoints import compile_router, history_router, stats_router
from db.database import init_db

# 初始化日志
logger.add("logs/py2so.log", rotation="10 MB", retention="7 days")

# 创建FastAPI应用
app = FastAPI(
    title="Py2SO API",
    description="将Python文件编译为二进制模块的后端服务",
    version="1.0.0"
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境中应指定具体的前端域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 确保所需目录存在
UPLOAD_DIR = Path("uploads")
OUTPUT_DIR = Path("outputs")
LOGS_DIR = Path("logs")

for dir_path in [UPLOAD_DIR, OUTPUT_DIR, LOGS_DIR]:
    dir_path.mkdir(parents=True, exist_ok=True)

# 注册路由
app.include_router(compile_router, prefix="/api/compile", tags=["编译"])
app.include_router(history_router, prefix="/api/history", tags=["历史记录"])
app.include_router(stats_router, prefix="/api/stats", tags=["统计数据"])

# 挂载静态文件目录
app.mount("/outputs", StaticFiles(directory=str(OUTPUT_DIR)), name="outputs")

@app.get("/", response_class=HTMLResponse)
async def read_root():
    index_path = os.path.join(os.path.dirname(__file__), "../index.html")
    with open(index_path, "r") as f:
        return HTMLResponse(content=f.read())

# 挂载前端静态文件
app.mount("/", StaticFiles(directory=os.path.abspath("../"), html=True), name="frontend")

# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error(f"全局异常: {str(exc)}")
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={"message": "服务器内部错误", "detail": str(exc)}
    )

# 初始化数据库
@app.on_event("startup")
async def startup_event():
    init_db()
    logger.info("Py2SO服务启动成功")

# 健康检查接口
@app.get("/api/health", tags=["系统"])
async def health_check():
    return {"status": "healthy", "service": "py2so-backend"}

# 启动应用
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
